<template>
  <el-table
    :data="
      tableData.filter(
        (data) =>
          !search || data.name.toLowerCase().includes(search.toLowerCase())
      )
    "
  >
    <el-table-column align="center" label="图片">
      <template #default="scope">
        <el-image
          style="width: 80px; height: 80px"
          :src="src + scope.row.photo1"
        ></el-image>
      </template>
    </el-table-column>
    <el-table-column align="center" label="商品名称" prop="name" />
    <el-table-column align="center" label="库存">
      <template #default="scope">
        <el-tag :type="scope.row.inventory > 0 ? 'success' : 'danger'">
          {{ scope.row.inventory }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column align="center" label="分类" prop="classify_id" />
    <el-table-column align="center" label="价格" prop="price" />
    <el-table-column align="center">
      <template #header>
        <el-input
          v-model="search"
          size="mini"
          :suffix-icon="Search"
          placeholder="输入商品名称搜索商品"
        />
      </template>
      <template #default="scope">
        <el-button
          size="mini"
          type="primary"
          @click="
            (goodsEditDialog = true), handleGoodsEdit(scope.$index, scope.row)
          "
        >
          修改
        </el-button>
        <el-button
          size="mini"
          type="danger"
          @click="(goodsOutDialog = true), handleGoodsAdd(scope.row)"
        >
          下架
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 修改商品模态框 -->
  <el-dialog v-model="goodsEditDialog" title="修改商品">
    <el-form :model="edit">
      <el-form-item label="商品名称" :label-width="formLabelWidth">
        <el-input
          v-model="edit.name"
          autocomplete="off"
          maxlength="60"
        ></el-input>
      </el-form-item>
      <el-form-item label="🦉" :label-width="formLabelWidth">
        <div style="width: 50%">
          <input-image class="AddImg" v-model="edit.avatar" />
        </div>
      </el-form-item>
      <el-form-item label="商品价格" :label-width="formLabelWidth">
        <el-input
          v-model="edit.price"
          autocomplete="off"
          type="number"
          oninput="if(value.length>9)value=value.slice(0,9)"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品分类" :label-width="formLabelWidth">
        <el-select v-model="edit.classify_id" filterable placeholder="商品类型">
          <el-option
            v-for="item in classify"
            :label="item.name"
            :value="item.id"
            :key="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品简介" :label-width="formLabelWidth">
        <el-input
          v-model="edit.label"
          autocomplete="off"
          maxlength="255"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="goodsEditDialog = false">取消</el-button>
        <el-button type="primary" @click="goodsEdit()"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 下架模态框 -->
  <el-dialog v-model="goodsOutDialog" title="商品下架" width="30%" center>
    <el-text align="center">是否该下架商品</el-text>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="goodsOutDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            (goodsOutDialog = false), goodsOut(), (centerDialogVisible = true)
          "
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { onBeforeMount, ref, reactive, watch, toRefs } from "vue";
import InputImage from "./InputImage.vue";
import { goodsApi, goodsEditApi, goodsOutApi, classifyApi } from "@/api/goods";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";

export default {
  components: {
    InputImage,
  },
  props: {
    sum: String,
  },
  setup(props) {
    const src = ref("/avatars/");
    const search = ref("");
    const goodsEditDialog = ref(false);
    const { sum } = toRefs(props);
    let tableData = ref([]);
    const classify = reactive([]);
    let goodsIndex = null;
    // 获取上架商品数据&获取商品分类数据
    onBeforeMount(async () => {
      await goodsApi().then((res) => {
        tableData.value.push(...res.data.query.goods_stock);
        console.log(res.data.query);
      });
      await classifyApi().then((res) => {
        const data = res.data.query.result.map((item) => {
          item.validity == "1"
            ? (item.validity = true)
            : (item.validity = false);
          return item;
        });
        Object.assign(classify, data);
      });
    });
    // 声明变量用来接收对应商品
    const data = reactive({
      goods_id: "",
      state: "",
    });
    const edit = reactive({
      goods_id: "",
      state: "",
      name: "",
      price: "",
      label: "",
      classify_id: "",
      avatar: null,
    });
    // 获取对应商品的数据并赋值
    const handleGoodsAdd = (row) => {
      data.goods_id = row.id;
      data.state = row.state;
    };
    const handleGoodsEdit = (index, row) => {
      edit.goods_id = row.id;
      edit.state = row.state;
      edit.name = row.name;
      edit.price = row.price;
      edit.label = row.label;
      edit.index = index;
      edit.classify_id = row.classify_id;
      goodsIndex = index;
      edit.avatar = src.value + row.photo1;
      console.log(row);
    };
    // 修改商品操作
    const goodsEdit = () => {
      if (
        edit.state == "" ||
        edit.name == "" ||
        edit.price == "" ||
        edit.label == "" ||
        edit.classify_id == "" ||
        edit.avatar == null
      ) {
        ElMessage({
          message: "商品信息填写不全,请填写完成后提交.",
          type: "error",
        });
      } else {
        if (typeof edit.avatar == "object") {
          // 通过formData格式向服务器端发送数据
          const formData = new FormData();
          // 处理文件上传表单项
          Object.entries(edit).forEach(([k, v]) => {
            if (k == "avatar") {
              if (v) formData.append(k, v, v.name);
            } else formData.append(k, v);
          });
          goodsEditApi(formData).then((res) => {
            if (res.data.success) {
              ElMessage({
                message: "商品修改成功.",
                type: "success",
              });
              const data = res.data.goods_new;
              if (res.status == 200) {
                tableData.value.splice(goodsIndex, 1, data);
                console.log(tableData.value);
              }
              goodsEditDialog.value = false;
            }
          });
        } else {
          let img = edit.avatar.split("/");
          edit.avatar = img[img.length - 1];
          goodsEditApi(edit).then((res) => {
            if (res.data.success) {
              ElMessage({
                message: "商品修改成功.",
                type: "success",
              });
              const data = res.data.goods_new;
              if (res.status == 200) {
                tableData.value.splice(goodsIndex, 1, data);
                console.log(tableData.value);
              }
              goodsEditDialog.value = false;
            }
          });
        }
      }
    };
    // 下架商品操作
    const goodsOut = () => {
      goodsOutApi(data).then((res) => {
        if (res.data.success) {
          ElMessage({
            message: "商品下架成功.",
            type: "success",
          });
          tableData.value = tableData.value.filter((item) => {
            return item.id !== data.goods_id;
          });
        }
      });
    };
    watch(sum, () => {
      goodsApi().then((res) => {
        tableData.value = res.data.query.goods_stock;
      });
    });
    return {
      edit,
      tableData,
      classify,
      handleGoodsAdd,
      handleGoodsEdit,
      goodsEdit,
      goodsOut,
      goodsEditDialog,
      goodsOutDialog: ref(false),
      Search,
      search,
      src,
    };
  },
};
</script>
<style>
@media screen and (max-width: 600px) {
  .el-dialog {
    margin: 0px;
    width: 100%;
  }
  .cell .el-button--danger {
    margin-left: 0px;
  }
}
</style>
